package top.braycep.task;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import top.braycep.bean.VersionInfo;
import top.braycep.ui.MainUI;
import top.braycep.utils.AppUtils;
import top.braycep.utils.UpdateUtils;

import javax.swing.*;
import java.io.File;
import java.io.FileOutputStream;

public class DownloadTask extends SwingWorker {
    private static final Log LOG = LogFactory.get(DownloadTask.class);

    private MainUI mainUI;

    private File file;

    private boolean downloadSuccess;

    private String expMsg;

    public DownloadTask(MainUI mainUI) {
        this.mainUI = mainUI;
    }

    @Override
    protected Object doInBackground() throws Exception {
        if (UpdateUtils.hasUpdate()) {
            VersionInfo versionInfo = UpdateUtils.getVersionInfo();
            file = FileUtil.newFile(versionInfo.getLocalPath());

            if (file.exists()) {
                file.delete();
            }
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            file.createNewFile();

            if (versionInfo.getDownloadUrl() != null) {
                HttpUtil.download(versionInfo.getDownloadUrl(), new FileOutputStream(file), true);
                downloadSuccess = true;
                return null;
            }
        }

        downloadSuccess = false;
        return null;
    }

    @Override
    protected void done() {
        if (downloadSuccess) {
            LOG.info("Download Success, Path: {}", file.getAbsolutePath());
            AppUtils.showInfo(mainUI, "提示", "下载完成(" + file.getAbsolutePath() + ")");
        } else {
            LOG.info("Download Failed: {}", expMsg);
            AppUtils.showError(mainUI, "错误", "下载失败: " + expMsg);
        }
    }
}
